<script setup lang="ts" name="Index">
import { ElDialog, ElMessage } from 'element-plus'
import { createForm } from '@formily/core'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import SchemaForm from '@/components/SchemaForm'
import { updateUserPwd } from '@/api/system/user'

const currentUser = useUserStore()
const router = useRouter()

const form = createForm<{ oldPassword: string; newPassword: string; rePassword: string }>()

const schema = {
  type: 'object',
  properties: {
    layout: {
      'type': 'void',
      'x-component': 'FormLayout',
      'x-component-props': {
        labelWidth: 150,
      },
      'properties': {
        oldPassword: {
          'type': 'string',
          'x-component': 'Input',
          'x-decorator': 'FormItem',
          'title': '旧密码',
          'required': true,
          'x-component-props': {
            type: 'password',
            autoComplete: 'off',
            placeholder: '输入密码，注意初始密码是：Gyrw@123',
          },
        },
        newPassword: {
          'type': 'string',
          'x-component': 'Input',
          'x-decorator': 'FormItem',
          'title': '新密码',
          'required': true,
          'x-component-props': {
            type: 'password',
            autoComplete: 'off',
            placeholder: '输入一个简单好记的密码，记在小本本上',
          },
        },
        rePassword: {
          'type': 'string',
          'x-component': 'Input',
          'x-decorator': 'FormItem',
          'title': '重新输入新密码',
          'required': true,
          'x-component-props': {
            type: 'password',
            autoComplete: 'off',
            placeholder: '密码搞丢了要一天后才能找回，超级麻烦',
          },
        },
      },
    },
  },
}

function submit() {
  form.submit(async (values) => {
    if (values.rePassword !== values.newPassword) {
      ElMessage.error({ message: '两次密码不一致' })
      return
    }
    await updateUserPwd(values.oldPassword, values.newPassword)
    await currentUser.getInfo()
  })
}
async function cancel() {
  await currentUser.logOut()
  await router.replace({ name: 'login' })
}
</script>

<template>
  <div class="app-container home">
    首页
  </div>

  <ElDialog
    :model-value="!currentUser.passwordStatus"
    title="修改密码"
    lock-scroll
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :show-close="false"
    width="600"
  >
    <SchemaForm :schema="schema" :form="form" />
    <template #footer>
      <div class="dialog-footer">
        <ElButton type="primary" @click="submit">
          确 定
        </ElButton>
        <ElButton @click="cancel">
          取 消
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>
